package log

import (
	"fmt"
	"io"
	"os"
	"time"

	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	"github.com/sirupsen/logrus"
)

var L *logrus.Logger

func NewLogger(c *Config) (*logrus.Logger, error) {
	if c == nil {
		return nil, fmt.Errorf("config is nil")
	}

	if err := c.Validate(); err != nil {
		return nil, err
	}

	savePath := c.SavePath

	writer, err := rotatelogs.New(
		fmt.Sprintf("%s.%s", savePath, c.Suffix),
		rotatelogs.WithLinkName(savePath),
		rotatelogs.WithMaxAge(time.Duration(c.MaxAge)*time.Second),
		rotatelogs.WithRotationTime(time.Duration(c.RotationTime)*time.Second),
	)
	if err != nil {
		return nil, fmt.Errorf("failed to create log writer: %v", err)
	}

	level, err := logrus.ParseLevel(c.Level)
	if err != nil {
		return nil, err
	}

	L = logrus.New()

	L.SetLevel(level)

	if c.Debug {
		L.SetOutput(os.Stdout)
		L.SetFormatter(&logrus.TextFormatter{
			TimestampFormat: "2006-01-02 15:04:05.000000",
		})
	} else {
		L.SetOutput(io.MultiWriter(os.Stdout, writer))
		L.SetFormatter(&logrus.JSONFormatter{
			TimestampFormat: "2006-01-02 15:04:05.000000",
		})
	}

	return L, nil
}

// Infof 输出info级别日志
func Infof(format string, args ...interface{}) {
	if L != nil {
		L.Infof(format, args...)
	}
}

// Errorf 输出error级别日志
func Errorf(format string, args ...interface{}) {
	if L != nil {
		L.Errorf(format, args...)
	}
}

// Warnf 输出warn级别日志
func Warnf(format string, args ...interface{}) {
	if L != nil {
		L.Warnf(format, args...)
	}
}
